import threading
import logging
import time

logging.basicConfig(level=logging.INFO)


def worker(tasks):
    for task in tasks:
        time.sleep(0.001)
        # 非阻塞锁
        if task.lock.acquire(False):
            logging.info('{} {} is begin to start ...'.format(threading.current_thread().name, task.name))
        else:
            logging.info('{} {} is working ...'.format(threading.current_thread().name, task.name))


# 定义公共资源，将类Task实例化成10个实例，即10把锁
class Task:
    def __init__(self, name):
        self.name = name
        self.lock = threading.Lock()


tasks = [Task('task-{}'.format(x)) for x in range(10)]

# 启动5个线程来执行，即一个实例会被5个线程共同执行。
for i in range(5):
    threading.Thread(target=worker, name='worker-{}'.format(i), args=(tasks,)).start()
